import sys
import datetime

from PyQt4 import QtGui, QtCore

from preferences_widget import Preferences
from calendar_widget import CalendarWidget
from calendar_table_widget import CalTable
from download_widget import DownloadWidget
from plugin_manager_widget import PluginManagerWidget
from show_plugins_widget import ShowPlugins
from about_widget import About
from notificator import Notificator
import language
from updater import Updater

class PyTvTray(QtGui.QWidget):
    
    def __init__(self, py):
        QtGui.QWidget.__init__(self)
        self.pytv = py
        self.lang = language.setup()
        self.db = py.db
        self.notif = py.notif
        
        pixmap = QtGui.QPixmap(self.pytv.images['pytv'])
        self.setWindowTitle('PyTv!')
        self.setWindowIcon(QtGui.QIcon(pixmap))

        self._nextEpi = False
        v_box = QtGui.QVBoxLayout(self)
        #Horizontal Text and Button
        h_boxText = QtGui.QHBoxLayout()
        self._text = QtGui.QLineEdit()
        self._text.setFixedWidth(200)
        self._addButton = QtGui.QPushButton('')
        self._addButton.setIcon(self.style().standardIcon(QtGui.QStyle.SP_ArrowRight))
        self._removeButton = QtGui.QPushButton('')
        self._removeButton.setIcon(self.style().standardIcon(QtGui.QStyle.SP_TrashIcon))
        h_boxText.addWidget(self._text)
        h_boxText.addWidget(self._addButton)
        h_boxText.addWidget(self._removeButton)
        #List
        self._seriesList = QtGui.QListWidget()
        self._load_series_list()
        #Add layouts
        v_box.addLayout(h_boxText)
        v_box.addWidget(QtGui.QLabel(self.lang['follow']))
        v_box.addWidget(self._seriesList)

        #Menu
        self._menu = QtGui.QMenu('PyTv')
        add = self._menu.addAction(self.style().standardIcon(QtGui.QStyle.SP_ArrowRight), self.lang['add'])
        delete = self._menu.addAction(self.style().standardIcon(QtGui.QStyle.SP_ArrowLeft), self.lang['remove'])
        self._submenu = self._menu.addMenu(self.style().standardIcon(QtGui.QStyle.SP_MessageBoxInformation), self.lang['series'])
        todayEpisodes = self._submenu.addAction(self.style().standardIcon(QtGui.QStyle.SP_ArrowUp), self.lang['today'])
        calendar = self._submenu.addAction(QtGui.QIcon(self.pytv.images['calendar']), self.lang['calendar'])
        nextEpisode = self._submenu.addAction(self.style().standardIcon(QtGui.QStyle.SP_MessageBoxQuestion), self.lang['next'])
        download = self._submenu.addAction(self.style().standardIcon(QtGui.QStyle.SP_ArrowDown), self.lang['download'] + 's')
        refresh = self._submenu.addAction(self.style().standardIcon(QtGui.QStyle.SP_BrowserReload), self.lang['refresh'])
        self._menuPlugins = self._menu.addMenu(self.style().standardIcon(QtGui.QStyle.SP_DriveNetIcon), self.lang['plugins'])
        preferences = self._menu.addAction(self.style().standardIcon(QtGui.QStyle.SP_FileDialogListView), self.lang['preferences'])
        update = self._menu.addAction(QtGui.QIcon(self.pytv.images['update']), self.lang['update'])
        about = self._menu.addAction(QtGui.QIcon(self.style().standardIcon(QtGui.QStyle.SP_MessageBoxQuestion)), self.lang['about'])
        self.exit = self._menu.addAction(self.style().standardIcon(QtGui.QStyle.SP_TitleBarCloseButton), self.lang['exit'])
        self._plugManager = self._menuPlugins.addAction(self.style().standardIcon(QtGui.QStyle.SP_DriveNetIcon), self.lang['manager'])
        self._menuShowPlugins = self._menuPlugins.addMenu(self.lang['show'])
        
        self.load_menu_plugins()

        #SIGNAL->SLOT
        self.connect(self.exit, QtCore.SIGNAL("triggered()"), QtCore.QCoreApplication.quit)
        self.connect(self._menu, QtCore.SIGNAL("clicked()"), lambda: self._menu.popup(QtGui.QCursor.pos()))
        self.connect(add, QtCore.SIGNAL("triggered()"), self._add_serie_window)
        self.connect(delete, QtCore.SIGNAL("triggered()"), self._delete_serie_window)
        self.connect(calendar, QtCore.SIGNAL("triggered()"), self._view_calendar)
        self.connect(self._text, QtCore.SIGNAL("returnPressed()"), self._add_new_serie)
        self.connect(preferences, QtCore.SIGNAL("triggered()"), self._open_preferences)
        self.connect(self._addButton, QtCore.SIGNAL("clicked()"), self._add_new_serie)
        self.connect(self._removeButton, QtCore.SIGNAL("clicked()"), self._delete_existing_serie)
        self.connect(self._seriesList, QtCore.SIGNAL("itemSelectionChanged()"), self._list_clicked)
        self.connect(nextEpisode, QtCore.SIGNAL("triggered()"), self._next_episode_from)
        self.connect(todayEpisodes, QtCore.SIGNAL("triggered()"), self._show_today_episodes)
        self.connect(refresh, QtCore.SIGNAL("triggered()"), self._refresh_notificator)
        self.connect(download, QtCore.SIGNAL("triggered()"), self._download_info)
        self.connect(update, QtCore.SIGNAL("triggered()"), self._update)
        self.connect(about, QtCore.SIGNAL("triggered()"), self._about)
        self.connect(self._plugManager, QtCore.SIGNAL("triggered()"), self._show_plugin_manager)
        
        #SystemTray
        self._tray = QtGui.QSystemTrayIcon(QtGui.QIcon(pixmap), self)
        self._tray.setToolTip('PyTv')
        self._tray.setVisible(True)
        self._tray.setContextMenu(self._menu)
        
    def _load_series_list(self):
        series = self.db.restore_series()
        self._seriesList.clear()
        for s in series:
            self._seriesList.addItem(str(s))
            
    def load_menu_plugins(self):
        #Add Plugins
        self._menuShowPlugins.clear()
        plugins = self.pytv.plugins.get_active_show_plugins()
        for plugin in plugins:
            plugItem = self._menuShowPlugins.addAction(QtGui.QIcon(self.pytv.pluginFolder + plugin[0]), plugin[1])
            self.connect(plugItem, QtCore.SIGNAL("triggered()"), self._show_plugin_open)
            
    def _update(self):
        if Updater._newVersion:
            update = Updater()
            update.execute = update.update
            update.start()
        else:
            self.notif.show_message(self.lang['notNewVersion'], '')

    def _open_preferences(self):
        pref = Preferences(self, self.notif, self.db)
        pref.show()

    def _refresh_notificator(self):
        noti = Notificator()
        noti.execute = noti.refresh
        noti.start()

    def _download_info(self):
        downloads = self.notif.download_info()
        if len(downloads) > 0:
            down = DownloadWidget(self, downloads)
            down.show()
        else:
            self.notif.show_message(self.lang['notInfo'], '')

    def _next_episode_from(self):
        self._addButton.hide()
        self._removeButton.hide()
        self._text.setEnabled(False)
        self._nextEpi = True
        self.setVisible(True)

    def _show_today_episodes(self):
        table = CalTable(self, self.db)
        table.show()

    def _add_serie_window(self):
        self._text.clear()
        self._text.setEnabled(True)
        self.setVisible(True)
        self._removeButton.hide()
        self._addButton.show()
        self._text.setFocus()

    def _delete_serie_window(self):
        self._text.setEnabled(False)
        self.setVisible(True)
        self._addButton.hide()
        self._removeButton.show()

    def _list_clicked(self):
        try:
            self._text.setText(self._seriesList.item(self._seriesList.currentRow()).text())
            if self._nextEpi:
                s = str(self._text.text())
                date = datetime.date.today()
                cal = self.db.search_next_episode(s, date)
                serie = cal.serie.upper() + ': ' + self.lang['nextEpi'] + '(' + str(cal.date) + ')'
                episode = self.lang['season'] + ': ' + str(cal.season) + '\n'\
                 + self.lang['episode'] + ': ' + str(cal.nroEp) + ' - ' + cal.episode
                self.notif.show_message(serie, episode)
        except:
            if self._nextEpi:
                self.notif.show_message(self.lang['nextEpiNot'], '')
            print 'List with 0 elements'

    def _add_new_serie(self):
        s = str(self._text.text())
        series = [str(self._seriesList.item(i).text()) for i in range(self._seriesList.count())]
        if s not in series and len(s) > 0:
            self._seriesList.addItem(s)
            self.db.store_series(s)
            self._text.clear()
            self._seriesList.sortItems()

    def _delete_existing_serie(self):
        pos = self._seriesList.currentRow()
        if(pos > -1):
            serie = str(self._seriesList.takeItem(pos).text())
            self.db.delete_series(serie)
        self._text.clear()
        self._list_clicked()

    def _view_calendar(self):
        cal = CalendarWidget(self)
        cal.show()
        
    def _show_plugin_manager(self):
        manager = PluginManagerWidget(self)
        manager.show()
        
    def _show_plugin_open(self):
        showPlug = ShowPlugins(self)
        showPlug.show()
        
    def _about(self):
        ab = About(self)
        ab.show()

    def closeEvent(self, event):
        event.ignore()
        self._nextEpi = False
        self.hide()

    def show(self):
        pass
